<?php
class Controller_Pay extends Controller
{
	public $tbl = 'pay_order_log';
	
	/**
	 * 控制初始化方法
	 */
	public function initialize()
	{
		Core::loadLang('pay');
	}
	
	/**
	 * (non-PHPdoc)
	 * @see Controller::index()
	 */
	public function index()
	{
		$this->form();
	}
	
	/**
	 * 填写充值表单信息
	 */
	public function form()
	{
		$idList = Cache::lRange(Pay::$pmlKey, 0, -1);
		// 当前的默认充值方式(默认网银)
		if (isset($_GET['pay_mode']) && ctype_digit($_GET['pay_mode']) && in_array($_GET['pay_mode'], $idList)) {
			$this->payMode = $_GET['pay_mode'];
		} else {
			$this->payMode = 1;
		}
		$payModeInfo = Pay::readPayMode($this->payMode);
		$this->payModeInfo = $payModeInfo;
		// 平台金币充值未登录不跳转到登录页，直接客户端根据变量判断后决定是否弹出登录框，提高页面的用户体验。
		if ($payModeInfo['chanel_sign'] == '' && !User::isLogined()) {
			$this->alertLoginForm = true;
		} else {
			$this->alertLoginForm = false;
		}
		
		// 所有充值方式列表
		$payModeList = Pay::getPayModeList();
		$this->payModeList = $payModeList;
		
		// 所有游戏列表
		$gameList = Game::getGameList();
		
		$this->display();
	}
	
	/**
	 * 确认提交的表单信息
	 */
	public function confirm() 
	{
		$uid = User::getUidByUsername($_POST['username']);
		if (!$uid) {
			$this->failure(Core::getLang('username_not_exist'));
		}
		$user = User::read($uid, 'from_channel_id,game_id,server_id,gold,gold_bond');
		
		$payTarget	= (int)$_POST['pay_target'];
		$payMode	= (int)$_POST['pay_method'];
		$payMoney	= (int)$_POST['pay_money'];
		$gameId		= (int)$_POST['game_id'];
		$serverId	= (int)$_POST['server_id'];
		// 计算兑换的金额比例
		$goldVal = $payMoney * $payModeInfo['exchange'];
		// 生成订单号
		$orderNo = Pay::generateOrderNo();
		
		$payModeInfo = Pay::readPayMode($payMode); 
		$this->payModeInfo = $payModeInfo;
		
		/***************金币充值***************/
		// 金币充值到游戏
		if ($payModeInfo['channel_id'] == 0) {
			if ($payTarget == 2) {
				$this->failure(Core::getLang('gold_cannto_payto_site'));
			}
			// 扣减金币记录
			$cid = 1;
			$content = Core::getLang('log_payto_gold');
			User::addVal($uid, -$goldVal, $cid, 'gold', $gameId, $serverId, $orderNo, $content);
		}
		// 充值到平台金币
		else if ($payTarget == 2) {
			// 添加金币记录
			$cid = 2;
			$content = Core::getLang('log_payby_gold');
			User::addVal($uid, $goldVal, $cid, 'gold', 0, 0, $orderNo, $content);
		}
		
		/***************使用支付平台充值***************/
		$model = new Model('pay_order_log');
		$data = array(
			'order_no'			=> $orderNo,
			'uid'				=> $uid,
			'username'			=> $user['username'],
			'from_channel_id'	=> $user['from_channel_id'],
			'user_game_id'		=> $user['game_id'],
			'user_server_id'	=> $user['server_id'],
			'game_id'			=> $gameId,
			'server_id'			=> $serverId,
			'ip'				=> Ip::ip2long(),
			'target'			=> $payTarget,
			'pay_channel'		=> $payModeInfo['channel_id'],
			'pay_mode'			=> $payMode,
			'pay_money'			=> $payMoney,
			'gold_value'		=> $goldVal,
			'create_time'		=> time(),
			'pay_time'			=> 0,
			'end_time'			=> 0,
			'status'			=> 0,
			'pay_game_status'	=> 0,
			'channel_order_no'	=> '',
		);
		$model->add($data);
	}
	
	/**
	 * 提交确认
	 */
	public function commit() 
	{
		$orderNo = $_POST['order_no'];
		unset($_POST['order_no']);
		$payMethod = M('pay_method');
		$method = $payMethod->where('id='.(int)$_POST['pay_method'])->find();
		// 添加跳转到第三方支付平台
		$this->gotoPayPlatform($method, $_POST['pay_money'], $orderNo);
	}
	
	/**
	 * 生成支付宝的表单
	 */
	protected function buildAlipayForm($method, $pay_money, $orderNo) 
	{
		include APP_PATH.'api/alipay/alipay_service.php';
		include APP_PATH.'api/alipay/alipay_config.php';
		
		$siteUrl = 'http://www.'.C('ROOT_DOMAIN').'/';
		$return_url = $siteUrl . 'api/payment/alipay_return.php';
// 		$notify_url = $siteUrl . 'api/payment/alipay_callback.php';
		$notify_url = 'http://www.591yo.com/api/payment/alipay_callback.php';
		$show_url = $siteUrl;
		
		if ($method['sign'] == 'directPay') {
			$defaultbank = '';
		} else {
			$defaultbank = $_POST['pay_bank'];
		}
		
		// 测试用,充值1分钱;
		$pay_money = 0.01;
		
		$subject = '591YO充值￥'.$pay_money;
		$parameter = array(
			'service'			=> 'create_direct_pay_by_user',  //交易类型
			'partner'			=> $partner,         //合作商户号
			'return_url'		=> $return_url,      //同步返回
			'notify_url'		=> $notify_url,      //异步返回
			'_input_charset'	=> $_input_charset,  //字符集，默认为GBK
			'subject'			=> $subject, //'Order ID ' . $order_id . ' of ' .$item_name,       //商品名称，必填
			'body'				=> '订单号：'.$orderNo,       //商品描述，必填
			'out_trade_no'		=> $orderNo,//'3',//date('Ymdhms'),     //商品外部交易号，必填（保证唯一性）
			'payment_type'		=> '1',              //默认为1,不需要修改
			'total_fee'			=> $pay_money,
// 			'price'				=> $pay_money,           //商品单价，必填（价格不能为0）
// 			'quantity'			=> '1',              //商品数量，必填
	
			'logistics_fee'		=>'0.00',        //物流配送费用
			'logistics_payment'	=>'BUYER_PAY',   //物流费用付款方式：SELLER_PAY(卖家支付)、BUYER_PAY(买家支付)、BUYER_PAY_AFTER_RECEIVE(货到付款)
			'logistics_type'	=>'EXPRESS',     //物流配送方式：POST(平邮)、EMS(EMS)、EXPRESS(其他快递)
	
			'paymethod'			=> $method['sign'],
			'defaultbank'		=> $defaultbank,
			// 防钓鱼配置
			'exter_invoke_ip'	=> $_SERVER['REMOTE_ADDR'],
			'anti_phishing_key'	=> query_timestamp($partner),
	
			'show_url'			=> $show_url, //商品相关网站
			'seller_email'		=> $seller_email     //卖家邮箱，必填
		);
		$alipay = new alipay_service($parameter, $key, $sign_type);
		return $alipay->build_form();
	}
	
	/**
	 * 创建易宝请求表单
	 * @param array $method
	 * @param int $pay_money
	 * @param unknown_type $orderNo
	 */
	protected function buildYeepayForm($method, $pay_money, $orderNo)  
	{
		include APP_PATH.'Common/yeepay/yeepayCommon.php';

		$siteUrl = 'http://www.'.C('ROOT_DOMAIN').'/';
		
		$p4_Cur		= 'CNY';
		$p5_Pid		= iconv('utf-8', 'gbk', '591YO充值￥'.$pay_money);
// 		$p5_Pid		= '591yo';
		$p6_Pcat	= '123';
		$p7_Pdesc	= '123';
		$p8_Url		= $siteUrl . 'api/payment/yeepay_callback.php';
		$pa_MP		= '123';
		$pd_FrpId	= $_POST['pd_FrpId'];
		$pr_NeedResponse = '1';
		$hmac = getReqHmacString($orderNo, $pay_money, $p4_Cur, $p5_Pid, $p6_Pcat,
								$p7_Pdesc, $p8_Url, $pa_MP, $pd_FrpId, 
								$pr_NeedResponse
						);
		$parameter = array(
			'p0_Cmd'			=> $p0_Cmd,
			'p1_MerId'			=> $p1_MerId,
			'p2_Order'			=> $orderNo,
			'p3_Amt'			=> $pay_money,
			'p4_Cur'			=> $p4_Cur,
			'p5_Pid'			=> $p5_Pid,
			'p6_Pcat'			=> $p6_Pcat,
			'p7_Pdesc'			=> $p7_Pdesc,
			'p8_Url'			=> $p8_Url,
			'p9_SAF'			=> $p9_SAF,
			'pa_MP'				=> $pa_MP,
			'pd_FrpId'			=> $pd_FrpId,
			'pr_NeedResponse'	=> $pr_NeedResponse,
			'hmac'				=> $hmac,
		);
		
		$html = '<form id="yeepayform" name="yeepay" action="'.$reqURL_onLine.'" method="post">';
		foreach ($parameter as $key=>$value) {
			$html .= '<input type="hidden" name="'.$key.'" value="'.$value.'" />'."\n";
		}
		$html .= '</form><script>document.forms["yeepayform"].submit();</script>';
		return $html;
	}
	
	/**
	 * 跳转到第三方支付平台
	 * @param int $pay_method 支付方式
	 * @param int $pay_money 支付金额
	 * @param int $orderNo 订单号
	 */
	protected function gotoPay($method, $pay_money, $orderNo)
	{
		switch ($method['chanel_sign'])
		{
			// 支付宝
			case 'alipay':
				$html = $this->buildAlipayForm($method, $pay_money, $orderNo);
				break;
				// 易宝
			case 'yeepay':
				// 易宝接口数据采用gbk
				header('content-type:text/html;charset=gbk');
				$html = $this->buildYeepayForm($method, $pay_money, $orderNo);
				break;
	
			default:
				;
				break;
		}
		echo $html;
		exit;
	}
	
	/**
	 * 易宝支付服务器点对点通讯回调
	 */
	public function yeepayCallback()
	{
		switch ($_GET['r9_BType'])
		{
			case '1':
				include APP_PATH.'api/yeepay/yeepaySave.php';
				$return = yeepaySave($_GET);
				if ($return) {
					$this->display('success');
				} else {
					$this->display('fail');
				}
				break;
				
			case '2':// 服务器点对点通讯,不需要提示界面
				include APP_PATH.'api/yeepay/yeepaySave.php';
				$res = Url::getContents($url);
				$return = yeepaySave($_GET);
				
				/**
				 * 收到易宝支付服务器点对点支付成功通知，必须回写以“success”（无关大小写）开头的字符串，
				 * 即使您收到成功通知时发现该订单已经处理过，也要正确回写“success”，
				 * 否则易宝支付将认为您的系统没有收到通知，启动重发机制，直到收到“success”为止。
				 */
				if ($return) {
					echo 'success';
				} else {
					echo 'failure';
				}
				exit;
				break;
		}
	}
	
	/**
	 * 支付宝支付服务器点对点通讯回调
	 */
	public function alipayCallback()
	{
		include APP_PATH.'api/alipay/alipaySave.php';
		$return = alipaySave($_GET, 'return');
		// 服务器点对点通讯,不需要提示界面
		include WEB_ROOT.'Common/alipay/alipaySave.php';
		$res = Url::getContents($url);
		$return = alipaySave($_GET);
	
		/**
		 * TRADE_FINISHED(表示交易已经成功结束，通用即时到帐反馈的交易状态成功标志);
		 * TRADE_SUCCESS(表示交易已经成功结束，高级即时到帐反馈的交易状态成功标志);
		 * 该服务器异步通知页面面主要功能是：对于返回页面（return_url.php）做补单处理。
		 * 如果没有收到该页面返回的 success 信息，支付宝会在24小时内按一定的时间策略重发通知
		 */
		if ($return) {
			echo 'success';
		} else {
			echo 'failure';
		}
		exit;
	}
	
}
